/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package musicplayer;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.filechooser.FileFilter;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.SourceDataLine;
import javax.swing.ButtonGroup;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javazoom.jlgui.basicplayer.BasicController;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerEvent;
import javazoom.jlgui.basicplayer.BasicPlayerException;
import javazoom.jlgui.basicplayer.BasicPlayerListener;
import javax.swing.JFileChooser;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.KeyStroke;
import org.tritonus.share.sampled.file.TAudioFileFormat;
/**
 *
 * @author Mr.D
 */

public class Manager extends JFrame implements ActionListener, DropTargetListener, BasicPlayerListener, Runnable, KeyListener{
    private JMenu menufile, menuview, menucontrol, menuitemoption,menuitemvisuals, menuitemallbar, menuitemallscope, menuitemallcircle, menuitemalltext, menuitemimage,  menuitemskin, menuitemvisual, menuitemplayoption, menuitemrepeat;
    private JMenuBar menubar;
    private JMenuItem menuitemexit, menuitemopenfile, menuitemopenfolder, menuitemplay, menuitempause, menuitemstop, menuitemprevious, menuitemnext, menuitemfileinfo, menuitemplaylist, menuitemoff, menuitemrealscope, menuitemslowscope, menuitembar, menuitemcircle, menuabout, menuitemabout, menuitemguide, menuitemcircle2, menuitemtext, showtext, menuitembar2, menuitemtext2, menuitemopenplaylist, menuitemsaveplaylist;
    private JMenuItem menuitemwater, menuitemhavesoul, menuitemcolors, menuitemlight;
    private JRadioButtonMenuItem menuitemskin1, menuitemskin2, menuitemskin3, menuitemskin4, menuitemskin5, menuitemskin6, menuitemskincustom;
    private ButtonGroup group;
    private SpectrumAnalyzer sa;
    private Map audioInfo = null;
    private File musicfile;
    private BasicPlayer mp;
    private JFileChooser fc;
    private FileFilter ff,ff2, ff3;//ff is file list, ff2 is folder, ff3 is playlist
    private String path, songname;
    private final byte STOP = 0;
    private final byte PLAY = 1;
    private final byte PAUSE = 2;
    private byte playerstate = STOP;
    private JButton bplay,bpause,bstop, bnext, bprevious;
    private JCheckBoxMenuItem menuitemontop, menuitemrepeatall, menuitemshuffle, menuitemrepeatcurrent, menuitemgravityeffect, menuitemboucheffect;
    private double lengthbytes, bytesperpixel, gain, pan, playingfilesize;
    private int blinkposition, songcount;
    private PlayList playlist;
    private File current_folder;
    private File[] songfiles;
    private String[] total_song;
    private String[] songlist;
    private int oldx, oldy;
    private boolean changeposition = true;
    private int playerx, playery;
    private int oldmode;
    private Dimension screensize;
    private Toolkit tk;
    
    private int realscreenwidth = 0;
    private int realscreenheight = 0;
    private String title = "", artist = "", album = "", year = "", type = "", channel = "",samplerate = "", bitrate = "", layer = "";
    private long duration =0;
    private boolean copyright = false, original = false;

    //Enable DnD
    private DropTargetAdapter dnd;

    //Luu lai playlist
    private String songliststore = "", urlliststore = "", optionstore = "", selectedfilepath = "";

    //Custom
    private Custom ct;
    private String usertext = "Mr.D", userimagepath = "lib/light_effect.jar";

    //use for gravity effect
    private Thread threadforgravity;
    private double gravityenabletime = 0;
    private boolean isgravityselected = false;
    private double gravitycurrenttime = 0;
    private double inivelocityy = 0;
    private double velocity_y  = 0;
    
    //use for bouch
    private int frameposx = 0;
    private int frameposy = 0;
    private boolean directionx = false;
    private boolean directiony = false;
    private boolean isrunning = true;
    private boolean isholding = false;
    private boolean isbouchselected = false;

    public Manager(){
        setAlwaysOnTop(true);
        setUndecorated(true);
        threadforgravity = new Thread(this);
        sa = new SpectrumAnalyzer();
        playlist = new PlayList(this);
        playlist.initialize();
        ct = new Custom(this);
        Properties props = System.getProperties();
        Iterator it = props.keySet().iterator();
        TreeMap map = new TreeMap();
            while (it.hasNext())
            {
                String key = (String) it.next();
                String value = props.getProperty(key);
                map.put(key, value);
            }
            it = map.keySet().iterator();
//        while (it.hasNext())
//            {
//                String key = (String) it.next();
//                String value = (String) map.get(key);
//                System.out.println(key + "=" + value + "\r\n");
//            }
        urlliststore = map.get("user.dir").toString()+"\\lib\\ul.str";
        songliststore = map.get("user.dir").toString()+"\\lib\\sl.str";
        optionstore = map.get("user.dir").toString()+"\\lib\\opt.str";
        File f = new File(urlliststore);
        char[] cbuf = new char[(int)f.length()];
        FileReader fr = null;
        if(f.isFile()&&f.exists()){
            try {
                fr = new FileReader(urlliststore);
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                fr.read(cbuf);
            } catch (IOException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        String songn = new String(cbuf);
        DefaultListModel model= new DefaultListModel();
        String currentsong = "";
        int beginlink = 0;
        for(int i = 0; i < songn.length(); i++){
            if(songn.charAt(i) == 10){
                currentsong = songn.substring(beginlink, i);
                beginlink = i+1;
                model.addElement(currentsong);
            }
        }
        playlist.setModelUrl(model);
        model.clear();
        f = new File(songliststore);
        cbuf = new char[(int)f.length()];
        if(f.isFile()&&(f.exists()))
            try {
                fr = new FileReader(songliststore);
            try {
                fr.read(cbuf);
            } catch (IOException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
        //10d la ma cua ky tu xuong dong o he decimal
        songn = new String(cbuf);
        model = new DefaultListModel(); 
        currentsong = "";
        beginlink = 0;
        for(int i = 0; i < songn.length(); i++){
            if(songn.charAt(i) == 10){
                currentsong = songn.substring(beginlink, i);
                beginlink = i+1;
                model.addElement(currentsong);
            }
        }
        playlist.setModelName(model);        
        tk = Toolkit.getDefaultToolkit();
        screensize = tk.getScreenSize();
//        Rectangle winSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();

        dnd = new DropTargetAdapter(){
            @Override
            public void processDrop(Object data)
            {
                processDnD(data);
            }
        };
        DropTarget dt = new DropTarget(sa, DnDConstants.ACTION_COPY, dnd, true);
        DropTarget dt1 = new DropTarget(playlist, DnDConstants.ACTION_COPY, dnd, true);
        total_song = new String[1];
        songlist = new String[1];
        songcount = 0;
        bplay = new JButton("►");
        bpause = new JButton("||");
        bstop = new JButton("■");
        bnext = new JButton("▼");
        bprevious = new JButton("▲");
        bnext.setEnabled(false);
        bprevious.setEnabled(false);
        bplay.setEnabled(false);
        bpause.setEnabled(false);
        bstop.setEnabled(false);
        //Co the gan skin bang cac cau lenh sau, nhung khong nen vi qua xau
//        bpause.setBackground(new Color(200,50,100));
//        bpause.setForeground(Color.GREEN);
//        bpause.setBackground(null);
        sa.setLayout(null);
        current_folder = null;
        //setBounds(260, 150, 305, 310);
        sa.add(bprevious);
        sa.add(bplay);
        sa.add(bpause);
        sa.add(bstop);
        sa.add(bnext);
        menubar = new JMenuBar();
        menubar.setBackground(new Color(0,70,90));
        menufile = new JMenu("File");
        menuitemvisuals = new JMenu("Visualizations");
        menucontrol = new JMenu("Control");       
        menuview = new JMenu("View");
        menuitemrepeat = new JMenu("Repeat");        
        menuitemplaylist = new JMenuItem("Playlist");
        menuitemplaylist.setToolTipText("Show Playlist");
        menuitempause = new JMenuItem("Pause");
        menuitempause.setToolTipText("Pause play back");
        menuitemexit = new JMenuItem("Exit");
        menuitemexit.setToolTipText("End this program");
        menuitemopenplaylist = new JMenuItem("Open Playlist");
        menuitemopenplaylist.setToolTipText("Open saved playlist");
        menuitemsaveplaylist = new JMenuItem("Save Playlist");
        menuitemsaveplaylist.setToolTipText("Save current playlist");
        menuitemnext = new JMenuItem("Next");
        menuitemnext.setToolTipText("Next song");
        menuitemprevious = new JMenuItem("Previous");
        menuitemprevious.setToolTipText("Previous song");
        menuitemfileinfo = new JMenuItem("File Info");
        menuitemfileinfo.setToolTipText("Show file info");
        
        menuitemoption = new JMenu("Options");        
        menuitemontop = new JCheckBoxMenuItem("Always On Top");
        menuitemontop.setToolTipText("Set allways on top");
        menuitemgravityeffect = new JCheckBoxMenuItem("Gravity");
        menuitemgravityeffect.setToolTipText("Use gravity effect");
        menuitemboucheffect = new JCheckBoxMenuItem("Bouching");
        menuitemboucheffect.setToolTipText("Use bouch effect");

        menuitemplayoption = new JMenu("Play");
        menuitemrepeatcurrent = new JCheckBoxMenuItem("Current");
        menuitemrepeatcurrent.setToolTipText("Repeat current song");
        menuitemrepeatall = new JCheckBoxMenuItem("All");
        menuitemrepeatall.setToolTipText("Repeat all song");
        menuitemshuffle = new JCheckBoxMenuItem("Shuffle");
        menuitemshuffle.setToolTipText("Shuffle all song");
        menuitemplay = new JMenuItem("Play");
        menuitemplay.setToolTipText("Start play back");
        menuitemstop = new JMenuItem("Stop");
        menuitemstop.setToolTipText("Stop play back");
        menuitemopenfile = new JMenuItem("Add File");
        menuitemopenfile.setToolTipText("Open a local mp3 file");
        menuitemopenfolder = new JMenuItem("Add Folder");
        menuitemopenfolder.setToolTipText("Open a folder that contain many mp3 file");
        menuitemoff = new JMenuItem("Null");
        menuitemoff.setToolTipText("No visualization");
        menuitemrealscope = new JMenuItem("Oscilliscope");
        menuitemrealscope.setToolTipText("Real time Oscilliscope");
        menuitemslowscope = new JMenuItem("Slow Oscilliscope");
        menuitemslowscope.setToolTipText("One band Oscilliscope");
        menuitemimage = new JMenu("Image");
        menuitemwater = new JMenuItem("Rain");
        menuitemwater.setToolTipText("Rain effect style");
        menuitemhavesoul = new JMenuItem("Soul");
        menuitemhavesoul.setToolTipText("Sword soul effect style");
        menuitemvisual = new JMenu("Visual");
        menuitemcolors = new JMenuItem("Colors");
        menuitemcolors.setToolTipText("Colors and shapes style");
        menuitemlight = new JMenuItem("Light");
        menuitemlight.setToolTipText("Light style");
        menuitemskin = new JMenu("Skin");
        group = new ButtonGroup();
        menuitemskin1 = new JRadioButtonMenuItem("Default");
        menuitemskin1.setToolTipText("Default skin, reset all setting");
        menuitemskin1.setSelected(true);
        menuitemskin2 = new JRadioButtonMenuItem("DARK");
        menuitemskin2.setToolTipText("Dark skin");
        menuitemskin3 = new JRadioButtonMenuItem("LIGHT");
        menuitemskin3.setToolTipText("Light skin");
        menuitemskin4 = new JRadioButtonMenuItem("RED");
        menuitemskin4.setToolTipText("Red skin");
        menuitemskin5 = new JRadioButtonMenuItem("GREEN");
        menuitemskin5.setToolTipText("Green skin");
        menuitemskin6 = new JRadioButtonMenuItem("BLUE");
        menuitemskin6.setToolTipText("More skin in full version");
        menuitemskincustom = new JRadioButtonMenuItem("Custom");
        menuitemskincustom.setToolTipText("Choose custom text and image");         
        



        menuitembar = new JMenuItem("Normal");
        menuitembar.setToolTipText("Normal style Bar");
        menuitembar2 = new JMenuItem("Line");
        menuitembar2.setToolTipText("Line style Bar");
        menuitemcircle = new JMenuItem("One");
        menuitemcircle.setToolTipText("One Circle style");
        menuitemcircle2 = new JMenuItem("Three");
        menuitemcircle2.setToolTipText("Three Circle style");
        menuitemtext = new JMenuItem("Many");
        menuitemtext.setToolTipText("Many text style");
        menuitemtext2 = new JMenuItem("One");
        menuitemtext2.setToolTipText("One text style");
        menuabout = new JMenu("Help");
        menuitemguide = new JMenuItem("How to Use");
        menuitemguide.setToolTipText("Show Help");
        menuitemabout = new JMenuItem("About");
        menuitemabout.setToolTipText("Program Information");
        showtext = new JMenuItem("Hide Comment");
        showtext.setToolTipText("Hide comment in all visualization");
        menuitemallbar = new JMenu("Bar");
        menuitemallscope = new JMenu("Scope");
        menuitemallcircle = new JMenu("Circle");
        menuitemalltext = new JMenu("Text");
        menufile.setMnemonic('F');
        menuitemopenfile.setMnemonic('i');
        menuitemopenfolder.setMnemonic('o');
        menuitemexit.setMnemonic('x');
        menuitemopenplaylist.setMnemonic('P');
        menuitemsaveplaylist.setMnemonic('S');
        menucontrol.setMnemonic('C');
        menuitemplay.setMnemonic('P');
        menuitempause.setMnemonic('a');
        menuitemstop.setMnemonic('S');
        menuitemnext.setMnemonic('n');
        menuitemprevious.setMnemonic('r');
        menuview.setMnemonic('V');
        menuitemvisuals.setMnemonic('s');
        menuitemoption.setMnemonic('O');
        menuitemfileinfo.setMnemonic('I');
        menuitemplaylist.setMnemonic('P');
        menuitemoff.setMnemonic('N');
        menuitemallscope.setMnemonic('S');
        menuitemrealscope.setMnemonic('O');
        menuitemslowscope.setMnemonic('l');
        menuitemallbar.setMnemonic('B');
        menuitembar.setMnemonic('N');
        menuitembar2.setMnemonic('L');
        menuitemallcircle.setMnemonic('C');
        menuitemcircle.setMnemonic('O');
        menuitemcircle2.setMnemonic('T');
        menuitemalltext.setMnemonic('T');
        menuitemtext.setMnemonic('M');
        menuitemtext2.setMnemonic('O');
        menuitemimage.setMnemonic('I');
        menuitemwater.setMnemonic('R');
        menuitemhavesoul.setMnemonic('S');
        menuitemvisual.setMnemonic('V');
        menuitemcolors.setMnemonic('C');
        menuitemlight.setMnemonic('L');
        showtext.setMnemonic('H');
        menuitemontop.setMnemonic('T');
        menuitemgravityeffect.setMnemonic('G');
        menuitemboucheffect.setMnemonic('B');
        menuitemplayoption.setMnemonic('P');
        menuitemrepeatcurrent.setMnemonic('C');
        menuitemrepeatall.setMnemonic('A');
        menuitemshuffle.setMnemonic('S');
        menuitemskin.setMnemonic('S');
        menuabout.setMnemonic('H');
        menuitemguide.setMnemonic('U');
        menuitemabout.setMnemonic('A');
        menuitemopenfile.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_DOWN_MASK));
        menuitemopenfolder.setAccelerator(KeyStroke.getKeyStroke('O', InputEvent.CTRL_DOWN_MASK));
        menuitemexit.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_DOWN_MASK));
        menuitemopenplaylist.setAccelerator(KeyStroke.getKeyStroke('P', InputEvent.CTRL_DOWN_MASK));
        menuitemsaveplaylist.setAccelerator(KeyStroke.getKeyStroke('T', InputEvent.CTRL_DOWN_MASK));
        menuitemplay.setAccelerator(KeyStroke.getKeyStroke('W', InputEvent.CTRL_DOWN_MASK));
        menuitempause.setAccelerator(KeyStroke.getKeyStroke('E', InputEvent.CTRL_DOWN_MASK));
        menuitemstop.setAccelerator(KeyStroke.getKeyStroke('R', InputEvent.CTRL_DOWN_MASK));
        menuitemnext.setAccelerator(KeyStroke.getKeyStroke('T', InputEvent.CTRL_DOWN_MASK));
        menuitemprevious.setAccelerator(KeyStroke.getKeyStroke('Y', InputEvent.CTRL_DOWN_MASK));
        menuitemontop.setAccelerator(KeyStroke.getKeyStroke('J', InputEvent.CTRL_DOWN_MASK));
        menuitemgravityeffect.setAccelerator(KeyStroke.getKeyStroke('G', InputEvent.CTRL_DOWN_MASK));
        menuitemboucheffect.setAccelerator(KeyStroke.getKeyStroke('B', InputEvent.CTRL_DOWN_MASK));
        menuitemrepeatcurrent.setAccelerator(KeyStroke.getKeyStroke('K', InputEvent.CTRL_DOWN_MASK));
        menuitemrepeatall.setAccelerator(KeyStroke.getKeyStroke('P', InputEvent.CTRL_DOWN_MASK));
        menuitemshuffle.setAccelerator(KeyStroke.getKeyStroke('L', InputEvent.CTRL_DOWN_MASK));
        menuitemplaylist.setAccelerator(KeyStroke.getKeyStroke('S', InputEvent.CTRL_DOWN_MASK));
        menuitemfileinfo.setAccelerator(KeyStroke.getKeyStroke('F', InputEvent.CTRL_DOWN_MASK));
        menuitemguide.setAccelerator(KeyStroke.getKeyStroke('H', InputEvent.CTRL_DOWN_MASK));
        menuitemabout.setAccelerator(KeyStroke.getKeyStroke('I', InputEvent.CTRL_DOWN_MASK));        
        menuitemskincustom.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_DOWN_MASK));        
        lengthbytes = 0;
        playingfilesize = 0;
        bytesperpixel = 0;
        blinkposition = 0;
        pan = 0;
        playerx = playery = 0;
        oldmode = 0;
        path = "";
        songname = "";
        fc = new JFileChooser();
        fc.setSelectedFile(null);
        mp = new BasicPlayer(); 
        menuitemontop.setState(true);
        gain = 1.414243;
        oldx = 0;
        oldy = 0;        
        menuitemopenfile.addActionListener(this);        
        menufile.add(menuitemopenfile);
        menufile.add(menuitemopenfolder);
        menucontrol.add(menuitemplay);
        menucontrol.add(menuitempause);
        menucontrol.add(menuitemstop);
        menucontrol.add(menuitemnext);
        menucontrol.add(menuitemprevious);
        menufile.add(menuitemopenplaylist);
        menufile.add(menuitemsaveplaylist);
        menufile.add(menuitemexit);        
        menuitemvisuals.add(menuitemoff);
        menuitemallscope.add(menuitemrealscope);
        menuitemallscope.add(menuitemslowscope);
        menuitemvisuals.add(menuitemallscope);
        menuitemallbar.add(menuitembar);
        menuitemallbar.add(menuitembar2);
        menuitemvisuals.add(menuitemallbar);
        menuitemallcircle.add(menuitemcircle);
        menuitemallcircle.add(menuitemcircle2);
        menuitemvisuals.add(menuitemallcircle);
        menuitemalltext.add(menuitemtext);
        menuitemalltext.add(menuitemtext2);
        menuitemvisuals.add(menuitemalltext);
        menuitemimage.add(menuitemlight);
        menuitemimage.add(menuitemwater);
        menuitemvisuals.add(menuitemimage);
        menuitemvisual.add(menuitemcolors);
        menuitemvisual.add(menuitemhavesoul);
        menuitemvisuals.add(menuitemvisual);
        menuitemvisuals.add(showtext);
        menuitemoption.add(menuitemontop);        
        menuitemrepeat.add(menuitemrepeatcurrent);
        menuitemrepeat.add(menuitemrepeatall);
        menuitemplayoption.add(menuitemrepeat);
        menuitemplayoption.add(menuitemshuffle);
        menuitemoption.add(menuitemplayoption);


        group.add(menuitemskin1);
        group.add(menuitemskin2);
        group.add(menuitemskin3);
        group.add(menuitemskin4);
        group.add(menuitemskin5);
        group.add(menuitemskin6);
        group.add(menuitemskincustom);


        menuitemskin.add(menuitemskin1);
//        menuitemskin.add(menuitemskin2);
//        menuitemskin.add(menuitemskin3);
//        menuitemskin.add(menuitemskin4);
//        menuitemskin.add(menuitemskin5);
//        menuitemskin.add(menuitemskin6);
        menuitemskin.add(menuitemskincustom);
        menufile.setForeground(Color.WHITE);
        menuview.setForeground(Color.WHITE);
        menucontrol.setForeground(Color.WHITE);
        menuabout.setForeground(Color.WHITE);



        menuitemoption.add(menuitemskin);
        menuabout.add(menuitemguide);
        menuabout.add(menuitemabout);
        menuview.add(menuitemvisuals);
        
        menuview.add(menuitemoption);
        menuview.add(menuitemfileinfo);
        menuview.add(menuitemplaylist);
        menuview.add(menuitemgravityeffect);
        menuview.add(menuitemboucheffect);
        menubar.add(menufile);
        menubar.add(menucontrol);
        menubar.add(menuview);
        menubar.add(menuabout);
        menucontrol.setEnabled(false);
        menuview.setEnabled(false);
        menuabout.setEnabled(false);
        this.setResizable(false);
        this.setTitle("JMusicPlayer");
        this.setJMenuBar(menubar);
        this.setContentPane(sa);
        this.setDropTarget(dt);
        playlist.setDropTarget(dt1);
        f = new File(optionstore);
        cbuf = new char[(int)f.length()];
        if(f.isFile()&&(f.exists()))
            try {
                fr = new FileReader(optionstore);
            try {
                fr.read(cbuf);
            } catch (IOException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
        songn = new String(cbuf);
        model = new DefaultListModel();
        currentsong = "";
        beginlink = 0;
        for(int i = 0; i < songn.length(); i++){
            if(songn.charAt(i) == 10){
                currentsong = songn.substring(beginlink, i);
                beginlink = i+1;
                model.addElement(currentsong);
            }
        }
        String [] options = new String[16];
        for(int i = 0; i < 16; i ++)
            options[i] = "0";
        for(int i = 0; i < model.getSize(); i++){
            options[i] = model.getElementAt(i).toString();
//            System.out.println(options[i]);
        }
        sa.setMode(Integer.parseInt(options[6]));
        if(Integer.parseInt(options[6]) == 0){
            setBounds(Integer.parseInt(options[0]), Integer.parseInt(options[1]), 300, 98);
            bprevious.setBounds(0,50, 60, 25);
            bplay.setBounds(60, 50, 60, 25);
            bpause.setBounds(120, 50, 60, 25);
            bstop.setBounds(180, 50, 60, 25);
            bnext.setBounds(240, 50, 60,25);
            sa.repaint();
        }
        else{
            setBounds(Integer.parseInt(options[0]), Integer.parseInt(options[1]), 300, 278);
            bplay.setBounds(60, 230, 60, 25);
            bprevious.setBounds(0,230, 60, 25);
            bpause.setBounds(120, 230, 60, 25);
            bstop.setBounds(180, 230, 60, 25);
            bnext.setBounds(240,230,60,25);
            sa.repaint();
        }
        playlist.setLocation(Integer.parseInt(options[2]), Integer.parseInt(options[3]));
        ct.setLocation(Integer.parseInt(options[4]), Integer.parseInt(options[5]));
        Image im;
        if((!options[7].equals("Mr.D")||(!options[8].isEmpty()&&!options[8].equals("lib/light_effect.jar")))&&(f.isFile())&&(f.exists())){
            im = getToolkit().getImage(options[8]);
            usertext = options[7];
            userimagepath = options[8];
            sa.setUserInfo(options[7], options[8]);
            menuitemskincustom.setSelected(true);
            if(userimagepath.equals("lib/light_effect.jar"))
                ct.setTexts(usertext, "");
            else
                ct.setTexts(usertext, userimagepath);
        }
        else{
            im = getToolkit().getImage("lib/audio_info1.1.jar");
            sa.setUserInfo("Mr.D", "lib/light_effect.jar");
            menuitemskincustom.setSelected(false);
        }
        if(userimagepath.equals("lib/light_effect.jar"))
            im = getToolkit().getImage("lib/audio_info1.1.jar");
        this.setIconImage(im);
        playlist.setIconImage(im);
        ct.setIconImage(im);
        if(options[9]!= null)
            selectedfilepath = options[9];
        if(playlist.getPlayListLength() != 0)
            playlist.setVisible(true);
        if(options[10].equals("hide")){
            sa.showText(false);
            showtext.setText("Show Comment");
            showtext.setToolTipText("Show comment in all visualization");
            showtext.setMnemonic('S');
        }
        else{
            sa.showText(true);
            showtext.setText("Hide Comment");
            showtext.setToolTipText("Hide comment in all visualization");
            showtext.setMnemonic('H');
        }
        if(options[11].equals("ontop")){
            setAlwaysOnTop(true);
            menuitemontop.setSelected(true);
            playlist.setAlwaysOnTop(true);
        }else{
            setAlwaysOnTop(false);
            menuitemontop.setSelected(false);            
            playlist.setAlwaysOnTop(false);
        }
        if(options[12].equals("shuffle")){
            menuitemshuffle.setState(true);
        }
        if(options[13].equals("current")){
            menuitemrepeatcurrent.setState(true);                      
        }else if(options[13].equals("all")){
            menuitemrepeatall.setState(true);
        }
            
        gain = Double.parseDouble(options[14]);   
        
        
//        gain = (e.getX()-12)*10/6;
//        if(gain == 0)
//            sa.setGainBarNum(-1, 0);
//        else
//            sa.setGainBarNum((int)(gain-1)/10, (int)gain);
//
//        gain /=100 * 1.414243;
//        System.out.println("gain == " + gain );
//        if(gain > mp.getMaximumGain())
//            gain = mp.getMaximumGain();
//        if(gain < mp.getMinimumGain())
//            gain = mp.getMinimumGain();
        if(gain > 1.414243)
            gain = 1.414243;
        if(gain < 0)
            gain = 0;




        pan = Double.parseDouble(options[15]); 
        double temppan = pan*50;
        sa.setPanPosition((int)(temppan+50)/2, (int)temppan*2);       
        try {
            mp.setGain(gain);
            mp.setPan(pan);
        } catch (BasicPlayerException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
        int tempgain = (int)(gain * 100/1.414243);
//        System.out.println("tempgain == " + tempgain);
        if(tempgain < 0)
            tempgain = 0;
        if(tempgain > 100)
            tempgain = 100;
        if(tempgain == 0)
            sa.setGainBarNum(-1, 0);
        else
            sa.setGainBarNum((int)(tempgain-1)/10, (int)tempgain);
//        sa.setMode(6);
//        playlist.setLocation(getX(), getY()+getHeight());
//        bpause.setEnabled(true);
//        bplay.setEnabled(true);
//        bprevious.setEnabled(true);


        ff = new FileFilter() {
            public boolean accept(File pathname) {
                if (pathname.isDirectory()) {
                    return true;
                }
                else
                {
                    String ext = "";
                    String s = pathname.getName();
                    int i = s.lastIndexOf('.');

                    if (i > 0 &&  i < s.length() - 1) {
                        ext = s.substring(i+1).toLowerCase();
                    }
                    if((ext.compareTo("mp1")==0)||(ext.compareTo("mp2")==0)||(ext.compareTo("mp3")==0)||(ext.compareTo("ogg")==0)||(ext.compareTo("wav")==0)||(ext.compareTo("wsz")==0)||(ext.compareTo("snd")==0)||(ext.compareTo("aifc")==0)||(ext.compareTo("aif")==0)||(ext.compareTo("au")==0)||(ext.compareTo("spx")==0)||(ext.compareTo("flac")==0)||(ext.compareTo("ape")==0)||(ext.compareTo("mac")==0))
                        return true;
                    else
                        return false;
                }
            }
            public String getDescription() {
                return "mp1,mp2,mp3,ogg,wav,wsz,snd,aifc,aif,au,spx,flac,ape,mac";
            }
        };
        ff2 = new FileFilter() {
        public boolean accept(File pathname) {
            if (pathname.isDirectory())
                return true;
            else
                return false;
        }
        public String getDescription() {
            return "Folder";
            }
        };
	ff3 = new FileFilter() {
        public boolean accept(File pathname) {
            if (pathname.isDirectory())
                return true;
            else
                return false;
        }
        public String getDescription() {
            return "*.jpl";
            }
        };
        fc.setFileFilter(ff);
        mp.addBasicPlayerListener(this);

        menuitemskincustom.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                ct.setVisible(true);
            }
        });
        menuitemskin1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                usertext = "Mr.D";
                userimagepath = "lib/audio_info1.1.jar";
                Image im = getToolkit().getImage(userimagepath);
                setIconImage(im);
                playlist.setIconImage(im);
                ct.setIconImage(im);
                userimagepath = "lib/light_effect.jar";
                sa.setUserInfo(usertext, userimagepath);
                sa.repaint();
            }
        });        
        menuitemnext.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                oldmode = sa.getMode();
                playlist.gotoNextSong();
            }
        });
        menuitemprevious.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                oldmode = sa.getMode();
                playlist.gotoPreviousSong();
            }
        });
        menuitemfileinfo.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                playlist.updateInfo(true, 0);
            }
        });
        menuitemopenfolder.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(!selectedfilepath.equals("")){
                File f = new File(selectedfilepath);
                    fc.setSelectedFile(f);
                }
                else
                    fc.setSelectedFile(null);
                fc.removeChoosableFileFilter(ff);
                fc.removeChoosableFileFilter(ff3);
                fc.setFileFilter(ff2);                
                fc.setDialogType(JFileChooser.SAVE_DIALOG);
                fc.setApproveButtonText("Select");
                fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                if(fc.showOpenDialog(sa) == JFileChooser.APPROVE_OPTION){
                    if((fc.getSelectedFile() != null)&&(fc.getSelectedFile().isDirectory())&&(fc.getSelectedFile().exists())){
                        selectedfilepath = fc.getSelectedFile().getPath();                        
                        path = fc.getSelectedFile()+"\\";
                        current_folder = new File(path);
                        songfiles = current_folder.listFiles();
                        if(songfiles.length>0){
                            songcount = 0;
                            for(int i = 0; i < songfiles.length; i++){
                                if((songfiles[i].isFile())&&(songfiles[i].toString().toLowerCase().endsWith(".mp3")))
                                    songcount ++;
                            }
                            total_song = new String[songcount];
                            songlist = new String[songcount];
                            for(int i = 0,j = 0; i < songfiles.length; i++){
                                if((songfiles[i].isFile())&&(songfiles[i].toString().toLowerCase().endsWith(".mp3"))){
                                    total_song[j] = songfiles[i].getName().toString();
                                    songlist[j] = path + songfiles[i].getName().toString();
                                    j++;
                                }
                            }
                            playlist.addSong(total_song, path);
                            playlist.addSong(songlist);
                            
                        }
                        if(total_song.length > 0){
                            menuview.setEnabled(true);
                            menuabout.setEnabled(true);
                            menucontrol.setEnabled(true);                            
                            if(playlist.getPlayListLength() == total_song.length){
                                songname = total_song[0];
                                Open();
                                Play();
                                sa.setXName(songname);
                                playlist.setCurrentIndex(0);
                                bplay.setEnabled(true);
                                bpause.setEnabled(true);
                                bstop.setEnabled(true);
                                bnext.setEnabled(false);
                                bprevious.setEnabled(false);
                                menuitemnext.setEnabled(false);
                                menuitemprevious.setEnabled(false);
                            }
                            if(playlist.getPlayListLength() > 1){                                
                                bnext.setEnabled(true);
                                bprevious.setEnabled(true);
                                menuitemnext.setEnabled(true);
                                menuitemprevious.setEnabled(true);
                            }
                            if(!playlist.isVisible()){
                                playlist.setLocation(getX(), getY()+getHeight());
                                playlist.setVisible(true);
                                
                            }
                        }
                        else
                            sa.setXName("");                        
                    }
                }
            }
        });
        menuitemopenplaylist.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                
            }
        });
        
        menuitemsaveplaylist.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fc.setDialogType(JFileChooser.SAVE_DIALOG);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                fc.removeChoosableFileFilter(ff);
                fc.removeChoosableFileFilter(ff2);
                fc.setFileFilter(ff3);
                if(fc.showSaveDialog(sa) == JFileChooser.APPROVE_OPTION){
					
                    System.out.println("Playlist saved");
                }
            }
        });
        menuitemplay.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(playerstate == PAUSE){
                    Resume();
                }
                else if(playerstate == STOP){                    
                    if(playlist.getPlayListLength() == 1)
                        playlist.gotoNextSong();
                    else
                        Play();
                }
                else{
                    oldmode = sa.getMode();
                    Stop();
                    Play();
                }
            }
        });        
        menuitemplaylist.addActionListener(new ActionListener() {
            

            public void actionPerformed(ActionEvent e) {
                playlist.setLocation(getX(), getY()+getHeight());
                playlist.setVisible(true);
            }
        });
        menuitemstop.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                oldmode = sa.getMode();
                Stop();
            }
        });
        menuitemexit.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){                
                try {
                    mp.stop();
                    sa.setXName("");
                    playerstate = STOP;
                } catch (BasicPlayerException ex) {}
                catch(Exception exc){}
                try {
                    FileWriter fw = new FileWriter(songliststore);
                    fw.write(playlist.listSong());
                    fw.close();
                    fw = new FileWriter(urlliststore);
                    fw.write(playlist.listUrl());
                    fw.close();
                    fw = new FileWriter(optionstore);
                    
                    fw.write(getX()+"\n"+getY()+"\n"+playlist.getX()+"\n"+playlist.getY()+"\n"+ct.getX()+"\n"+ct.getY()+"\n"+sa.getMode()+"\n"+usertext+"\n"+userimagepath+"\n"+selectedfilepath+"\n"+sa.getTextStatus()+"\n"+getOntopState()+"\n"+getShuffleState()+"\n"+getRepeatState()+"\n"+getGainNumber()+"\n"+getPanNumber()+"\n");
                    fw.close();
                } catch (IOException ex) {
                    Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.gc();
                System.exit(0);
            }
        });
        menuitembar.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(3);
                sa.setBar(true);
                sa.repaint();
            }
        });
        menuitembar2.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(3);
                sa.setBar(false);
                sa.repaint();
            }
        });
        menuitemcircle.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(4);
                sa.repaint();
            }
        });
        menuitemcircle2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(5);
                sa.repaint();
            }
        });
        menuitemslowscope.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(2);
                sa.repaint();
            }
        });
        menuitemwater.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(8);
                sa.repaint();
            }
        });
        menuitemhavesoul.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(9);
                sa.repaint();
            }
        });
        menuitemcolors.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(10);
                sa.repaint();
            }
        });
        menuitemlight.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(11);
                sa.repaint();
            }
        });
        menuitemrealscope.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
               sa.setMode(1);
               sa.repaint();
            }
        });
        menuitemtext.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(6);
                sa.repaint();
            }
        });
        menuitemtext2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
               sa.setMode(7);
               sa.repaint();
            }
        });
        menuitemguide.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(12);
                sa.repaint();
            }
        });
        menuitemabout.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                setBounds(getX(), getY(), 300, 278);
                bplay.setBounds(60, 230, 60, 25);
                bprevious.setBounds(0,230, 60, 25);
                bpause.setBounds(120, 230, 60, 25);
                bstop.setBounds(180, 230, 60, 25);
                bnext.setBounds(240,230,60,25);
                sa.setMode(13);
                sa.repaint();
            }
        });
        showtext.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if(showtext.getText().equals("Hide Comment") == true){
                    sa.showText(false);
                    showtext.setText("Show Comment");
                    showtext.setToolTipText("Show comment in all visualization");
                    showtext.setMnemonic('S');
                }
                else{
                    sa.showText(true);
                    showtext.setText("Hide Comment");
                    showtext.setToolTipText("Hide comment in all visualization");
                    showtext.setMnemonic('H');
                }
            }
        });
        menuitempause.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Pause();
            }
        });
        menuitemontop.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(isAlwaysOnTop() == true){
                    setAlwaysOnTop(false);
                    menuitemontop.setSelected(false);
                    playlist.setAlwaysOnTop(false);
                    ct.setAlwaysOnTop(false);
                }
                else{
                    setAlwaysOnTop(true);
                    menuitemontop.setSelected(true);
                    playlist.setAlwaysOnTop(true);
                    ct.setAlwaysOnTop(true);
                }
            }
        });     
        menuitemgravityeffect.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(menuitemgravityeffect.isSelected()){
                    menuitemboucheffect.setState(false);
                    isbouchselected = false;
                    playlist.setBouchState(false);
                    gravityenabletime = System.currentTimeMillis();
                    isgravityselected = true;
                    setEffectStartingPos();
                }
            }
        });
        menuitemboucheffect.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
               if(menuitemboucheffect.isSelected()){
                   isbouchselected = true;
                   setEffectStartingPos();
                   playlist.setBouchState(true);
                }else
                {
                   isbouchselected = false;
                   playlist.setBouchState(false);
                }
               menuitemgravityeffect.setState(false);
            }
        });
        menuitemrepeatcurrent.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(menuitemrepeatcurrent.isSelected()){
                    menuitemrepeatall.setState(false);
                }
            }
        });
        menuitemrepeatall.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(menuitemrepeatall.isSelected()){
                    menuitemrepeatcurrent.setState(false);
                    if(menuitemshuffle.isSelected())
                        playlist.contructShuffle();
                }
            }
        });
        menuitemshuffle.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(menuitemshuffle.getState() == true){
                    playlist.setShuffle(true);
                    playlist.contructShuffle();
                }
                else
                    playlist.setShuffle(false);
            }
        });
        menuitemoff.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {                         
                setBounds(getX(), getY(), 300, 98);
                bplay.setBounds(60, 50, 60, 25);
                bprevious.setBounds(0,50, 60, 25);
                bpause.setBounds(120, 50, 60, 25);
                bstop.setBounds(180, 50, 60, 25);
                bnext.setBounds(240,50,60,25);
                sa.setMode(0);
            }
        });               
        bplay.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if(playerstate == PAUSE){
                    Resume();
                }
                else if(playerstate == STOP)
                {
                    if(playlist.getPlayListLength() == 1)
                        playlist.gotoNextSong();
                    else
                        Play();
                }
                else{
                    oldmode = sa.getMode();
                    Stop();
                    Play();
                }
            };
        });
        bpause.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {                
                Pause();
            }
        });
        bstop.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                oldmode = sa.getMode();
                Stop();
            }
        });
        bnext.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                oldmode = sa.getMode();
                if(playlist.hasNext() ==  true){    
                    playlist.gotoNextSong();
                }else{
                    if(menuitemrepeatall.getState() == true){
                        if(menuitemshuffle.isSelected())
                            playlist.contructShuffle();
                        playlist.PlayFirstSong();

                    }else{
                        playlist.gotoNextSong();
                    }
                }
                menuitemplay.setEnabled(true);
                menuitempause.setEnabled(true);
                menuitemstop.setEnabled(true);
                bplay.setEnabled(true);
                bpause.setEnabled(true);
                bstop.setEnabled(true);
            }
        });
        bprevious.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                oldmode = sa.getMode();
                if(playlist.hasPrevious() ==  true){    
                    playlist.gotoPreviousSong();                    
                }else{
                    if(menuitemrepeatall.getState() == true){
                        if(menuitemshuffle.isSelected())
                            playlist.contructShuffle();
                        playlist.PlayLastSong();
                    }else{
                        playlist.gotoPreviousSong();
                    }
                }
                menuitemplay.setEnabled(true);
                menuitempause.setEnabled(true);
                menuitemstop.setEnabled(true);
                bplay.setEnabled(true);
                bpause.setEnabled(true);
                bstop.setEnabled(true);
            }
        });        
        this.addMouseListener(new MouseListener() {

            public void mouseClicked(MouseEvent e) {                
//                if((e.getY()>50)&&(e.getY()<252)&&(getHeight()==310)){
//                    int mode = sa.getMode();
//                    if(e.getButton()==MouseEvent.BUTTON1){
//                        mode ++;
//                        if(mode < 9){
//                            if((mode == 4)&&(sa.getBar() == true))
//                                sa.setBar(false);
//                            else{
//                                mode --;
//                                sa.setBar(true);
//                            }
//                        }
//                        else
//                            mode = 0;
//                        sa.setMode(mode);
//                    }
//                    else if(e.getButton() == MouseEvent.BUTTON3)
//                    {
//                        if(mode < 9){
//                            if((mode == 3)&&(sa.getBar() == true))
//                                sa.setBar(false);
//                            else
//                                mode --;
////                            if(mode == 2)
////                                sa.setBar(true);
//                        }
//                        if(mode == -1)
//                            mode = 8;
//                        sa.setMode(mode);
//                    }
//                }
            }

            public void mousePressed(MouseEvent e) {
                oldx = e.getX();
                oldy = e.getY();
                playerx = getX();
                playery = getY();
                isholding = true;
            }

            public void mouseReleased(MouseEvent e) {                
                if((getX()== playerx)||(getY()== playery)){
                    if((e.getY() > getHeight() - 40)&&(e.getY() < getHeight() - 28)){
                        seekBytes(e.getX());
                        sa.setBlinkPosition(e.getX());
                    }
                    if((e.getX() > 11)&&(e.getX() < 73) && (e.getY()>getHeight() - 53)&&(e.getY()<getHeight() - 40)){
                        sa.setControlSelected(1);
                        try {
                            gain = (e.getX()-12)*10/6;
                            if(gain == 0)
                                sa.setGainBarNum(-1, 0);
                            else
                                sa.setGainBarNum((int)(gain-1)/10, (int)gain);

                            gain /=100 * 1.414243;
                            if(gain > mp.getMaximumGain())
                                gain = mp.getMaximumGain();
                            if(gain < mp.getMinimumGain())
                                gain = mp.getMinimumGain();
                            
                            mp.setGain(gain);                            
//                            mp.setGain(1.414243);//Con so nay ung voi gia tri gain lon nhat, 0.0 la gi tri nho nhat
                        } catch (BasicPlayerException ex) {
                            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        catch(Exception exc){}
                    }
                    if((e.getX() > 5) && (e.getX() < 12) && (e.getY() > getHeight() - 53) && (e.getY() < getHeight() - 40))
                    {
                        try {
                            mp.setGain(0.0);
                        } catch (BasicPlayerException ex) {
                            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        sa.setControlSelected(1);
                        sa.setGainBarNum(-1, 0);
                    }
                    if((e.getX() > 232) && (e.getX() < 284) && (e.getY()>getHeight() - 54)&&(e.getY()<getHeight() - 42))
                    {
                        pan = ((e.getX()-233)*2)-50;
                        sa.setPanPosition((int)(pan+50)/2, (int)pan*2);
                        pan /=50.0;
                        try {
                            mp.setPan(pan);
                        } catch (BasicPlayerException ex) {
                            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        sa.setControlSelected(2);
                    }
                }
                isholding = false;
                setEffectStartingPos();
                gravityenabletime = System.currentTimeMillis();
            }

            public void mouseEntered(MouseEvent e) {
//                isholding = true;
            }

            public void mouseExited(MouseEvent e) {
                sa.setControlSelected(0);
//                isholding = false;
            }            
        });
        this.addMouseMotionListener(new MouseMotionListener() {

            public void mouseDragged(MouseEvent e) {
                int newx = getX();
                int newy = getY();
                if(changeposition){
                    if((getX() == 0)&&((e.getX()- oldx > 20)||(e.getX() - oldx < -20)))
                        setLocation(e.getXOnScreen() - oldx, newy);
                    if((getX() == (screensize.width - getWidth()))&&((oldx - e.getX() > 20)||(oldx - e.getX() < -20)))
                        setLocation(oldx - e.getXOnScreen(), newy);
                    if((getX() < 20)&&(getX() > - 20)){
                        setLocation(0, newy);
                    }
                    else if((getX()+ getWidth() > screensize.width - 20)&&((getX()+ getWidth() < screensize.width + 20)))
                        setLocation(screensize.width - getWidth(), newy);
                    else{
                            setLocation(e.getXOnScreen() - oldx, newy);
                    }
                    changeposition = false;
                }
                else{
                    if((getY() == 0)&&((e.getY()- oldy > 20)||(e.getY() - oldy < -20))){    
                            setLocation(newx, e.getYOnScreen() - oldy);
                    }
                    if((getY() == (screensize.height - getHeight()))&&((oldy - e.getY() > 20)||(oldy - e.getY() < -20)))
                        setLocation(newx, oldy - e.getYOnScreen());
                    if((getY() < 20)&&(getY() > - 20)){
                            setLocation(newx, 0);
                    }
                    else if((getY()+ getHeight() > screensize.height - 20)&&((getY() + getHeight() < screensize.height + 20)))
                        setLocation(newx, screensize.height - getHeight());
                    else{
                            setLocation(newx, e.getYOnScreen() - oldy);
                    }
                    changeposition = true;
                }
                isholding = true;
                setEffectStartingPos();
            }

            public void mouseMoved(MouseEvent e) {
                sa.setMousePosition(e.getX(), e.getY() - 20);
            }
        });
        this.addWindowListener(new WindowAdapter(){
            @Override
            public void windowClosing(WindowEvent e){
                try {
                    mp.stop();
                    sa.setXName("");
                    playerstate = STOP;
                } catch (BasicPlayerException ex) {}
                catch(Exception exc){}
                try {
                    FileWriter fw = new FileWriter(songliststore);
                    fw.write(playlist.listSong());
                    fw.close();
                    fw = new FileWriter(urlliststore);
                    fw.write(playlist.listUrl());
                    fw.close();
                    fw = new FileWriter(optionstore);
                    fw.write(getX()+"\n"+getY()+"\n"+playlist.getX()+"\n"+playlist.getY()+"\n"+ct.getX()+"\n"+ct.getY()+"\n"+sa.getMode()+"\n"+usertext+"\n"+userimagepath+"\n"+selectedfilepath+"\n"+sa.getTextStatus()+"\n"+getOntopState()+"\n"+getShuffleState()+"\n"+getRepeatState()+"\n"+getGainNumber()+"\n"+getPanNumber()+"\n");
                    fw.close();
                } catch (IOException ex) {
                    Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
                }
//                System.out.println(playlist.listSong());
                System.gc();
                System.exit(0);
            }
        });              
    }
    public void setEffectStartingPos(){
        frameposx = getX();
        frameposy = getY();
    }
    public void showFileInfo(boolean show,String path, String name) throws UnsupportedAudioFileException, IOException{
        getFileInfo(path, name);
        sa.setFileInfo(path, name, lengthbytes, type, layer, samplerate, bitrate, channel, duration, title, artist, album, year, original, copyright);
        if(show){
            setBounds(getX(), getY(), 300, 278);
            bplay.setBounds(60, 230, 60, 25);
            bprevious.setBounds(0,230, 60, 25);
            bpause.setBounds(120, 230, 60, 25);
            bstop.setBounds(180, 230, 60, 25);
            bnext.setBounds(240,230,60,25);
            sa.setMode(14);            
        }
        sa.repaint();
    }
    public void getFileInfo(String path, String name) throws UnsupportedAudioFileException, IOException{
        File selectedfile = new File(path+name);
        AudioFileFormat aff = null;
        aff = AudioSystem.getAudioFileFormat(selectedfile);        
        loadInfo(aff, path, name);
    }
    public void loadInfo(AudioFileFormat aff, String path, String name){
        Map props = aff.properties();
        if(aff instanceof TAudioFileFormat)
             props = ((TAudioFileFormat) aff).properties();
        lengthbytes = 0;
        this.type = "";
        this.layer = "";
        this.samplerate = "";
        this.bitrate = "";
        this.channel = "";
        duration = 0;
        this.title = this.artist = this.album = this.year = "";
        original = copyright = false;
        if(props.containsKey("audio.length.bytes"))
            lengthbytes = (double)Double.parseDouble(props.get("audio.length.bytes").toString());
        if(props.containsKey("audio.samplerate.hz"))
            samplerate = Float.toString((((Float)props.get("audio.samplerate.hz")).floatValue()/(float)1000));
        if (props.containsKey("audio.channels")) {
                int mode = ((Integer) props.get("audio.channels")).intValue();
                if (mode == 0) channel = "Stereo";
                else if (mode == 1) channel = "Joint Stereo";
                else if (mode == 2) channel = "Dual Channel";
                else if (mode == 3) channel = "Single Channel";
            }
        if(props.containsKey("audio.samplesize.bits"))
            bitrate = props.get("audio.samplesize.bits").toString();
        if(props.containsKey("duration"))
            duration = (((Long)props.get("duration")).longValue()/1000000);
        if(props.containsKey("title"))
            title = props.get("title").toString();
        if(props.containsKey("author"))
            artist = props.get("author").toString();
        if(props.containsKey("album"))
            album = props.get("album").toString();
        if(props.containsKey("date"))
            year = props.get("date").toString();
        if(props.containsKey("mp3.original"))
            original = ((Boolean) props.get("mp3.original")).booleanValue();
        if(props.containsKey("mp3.copyright"))
            copyright = ((Boolean) props.get("mp3.copyright")).booleanValue();
        if (props.containsKey("mp3.version.mpeg")) {
            String version = (String) props.get("mp3.version.mpeg");
            if (version.equals("1")) type = "MPEG1";
            else if (version.equals("2")) type = "MPEG2-LSF";
            else if (version.equals("2.5")) type = "MPEG2.5-LSF";
        }
        if (props.containsKey("mp3.version.layer"))
            layer = "Layer " + props.get("mp3.version.layer");
        if(props.containsKey("mp3.bitrate.nominal.bps"))
            bitrate = Integer.toString(((Integer)props.get("mp3.bitrate.nominal.bps")).intValue()/1000);
        if(props.containsKey("mp3.length.bytes"))
            lengthbytes = (double)Double.parseDouble(props.get("mp3.length.bytes").toString());
        if(props.containsKey("mp3.frequency.hz"))
            samplerate = Integer.toString(Integer.parseInt(props.get("mp3.frequency.hz").toString()));
        if (props.containsKey("mp3.channels")) {
                int mode = ((Integer) props.get("mp3.channels")).intValue();
                if (mode == 0) channel = "Stereo";
                else if (mode == 1) channel = "Joint Stereo";
                else if (mode == 2) channel = "Dual Channel";
                else if (mode == 3) channel = "Single Channel";
            }
        if(props.containsKey("mp3.samplesize.bits"))
            bitrate = props.get("mp3.samplesize.bits").toString();
    }
    public void opened(Object o, Map map) {
            audioInfo = map;
            if(audioInfo.containsKey("audio.length.bytes"))
                playingfilesize = (double)Double.parseDouble(audioInfo.get("audio.length.bytes").toString());
            if(audioInfo.containsKey("mp3.length.bytes"))
                playingfilesize = (double)Double.parseDouble(audioInfo.get("mp3.length.bytes").toString());
            bytesperpixel = playingfilesize/305;
    }

    public void progress(int i, long l, byte[] bytes, Map map) {
        processProgress(i, l, bytes, map);        
    }

    public void stateUpdated(BasicPlayerEvent bpe) {
        processStateUpdated(bpe);        
    }

    /*public void setController(BasicController bc) {
        this.control = bc;
        System.out.println("Tra loi tu setControler");
        if(control == null)
            System.out.println("Khong the set Control");
    }
     * 
     */
    private void processStateUpdated(BasicPlayerEvent event){
        int playstate = event.getCode();
        if (playstate == BasicPlayerEvent.EOM)
        {
            oldmode = sa.getMode();
            sa.stopDSP();            
            if(menuitemrepeatcurrent.getState() == true){
                //Stop();                
                Open();
                Play();
            }
            else if(playlist.hasNext() ==  true){                
                playlist.gotoNextSong();
            }else{
                if(menuitemrepeatall.getState() == true){
                    if(menuitemshuffle.isSelected())
                        playlist.contructShuffle();
                    playlist.PlayFirstSong();
                    
                }
            }
        }
        else if(playstate == BasicPlayerEvent.PLAYING)
        {
            if (audioInfo.containsKey("basicplayer.sourcedataline"))
            {
                sa.setupDSP((SourceDataLine) audioInfo.get("basicplayer.sourcedataline"));
                sa.startDSP((SourceDataLine) audioInfo.get("basicplayer.sourcedataline"));
            }
        }
        else if(playstate == BasicPlayerEvent.STOPPED){
            sa.stopDSP();
        }
    }
    public void processProgress(int bytesread, long microseconds, byte[] pcmdata, Map properties){                
        if (audioInfo.containsKey("basicplayer.sourcedataline"))
        {
            // Spectrum/time analyzer
            sa.writeDSP(pcmdata);
        }
        setBlinkPosition(bytesread);
    }
    public void actionPerformed(ActionEvent e) {
        if(!selectedfilepath.equals("")){
            File f = new File(selectedfilepath);
            fc.setSelectedFile(f);
        }
        else
            fc.setSelectedFile(null);
        fc.removeChoosableFileFilter(ff2);
        fc.removeChoosableFileFilter(ff3);
        fc.setFileFilter(ff);
        fc.setDialogType(JFileChooser.OPEN_DIALOG);
        fc.setApproveButtonText("Open");
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        if(fc.showOpenDialog(sa) == JFileChooser.APPROVE_OPTION){
            if((fc.getSelectedFile() != null)&&(fc.getSelectedFile().isFile())&&(fc.getSelectedFile().exists())){
                    selectedfilepath = fc.getSelectedFile().getPath();
                    path = fc.getSelectedFile().getParent() + "\\";
                    songname = fc.getSelectedFile().getName();
                    total_song = new String[1];
                    total_song[0] = songname;
                    playlist.addSong(total_song, path);
//                    playlist.addSong(selectedfilepath);
                    menuview.setEnabled(true);
                    menuabout.setEnabled(true);
                    menucontrol.setEnabled(true);
                    if (playlist.getPlayListLength() == 1) {
                        Open();
                        Play();
                        sa.setXName(songname);
                        playlist.setCurrentIndex(0);
                        bplay.setEnabled(true);
                        bpause.setEnabled(true);
                        bstop.setEnabled(true);
                        bnext.setEnabled(false);
                        bprevious.setEnabled(false);
                        menuitemnext.setEnabled(false);
                        menuitemprevious.setEnabled(false);                        
                    }  
                    else {                        
                        bnext.setEnabled(true);
                        bprevious.setEnabled(true);
                        menuitemnext.setEnabled(true);
                        menuitemprevious.setEnabled(true);                        
                    }                    
                    if(!playlist.isVisible()){
                        playlist.setLocation(getX(), getY()+getHeight());
                        playlist.setVisible(true); 
                    }
            }
        }
    }
    private void Open(){
        musicfile = new File(path+songname);        
        try {
            mp.open(musicfile);
        } catch (BasicPlayerException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void Play(){
        try {            
            mp.play();
            sa.setMode(oldmode);
//            sa.setXName(0);
            playerstate = PLAY;            
            sa.setStatus(1);
            mp.setGain(gain);
            mp.setPan(pan);
        } catch (BasicPlayerException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void Pause(){
        if(playerstate != STOP)
        try {
            oldmode = sa.getMode();
            sa.setMode(0);
            sa.setStatus(2);
            mp.pause();
            playerstate = PAUSE;
            sa.repaint();
        } catch (BasicPlayerException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void Stop(){
        try {            
            sa.setStatus(3);
            mp.stop();
            sa.setMode(0);
            playerstate = STOP;
            sa.repaint();
        } catch (BasicPlayerException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void Resume(){
        try {
            mp.resume();
            sa.setMode(oldmode);
            playerstate = PLAY;
            sa.setStatus(1);            
        } catch (BasicPlayerException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public void processPopupMenu(int state, String name, String songpath){
        if(state == 1){
            songname = name;
            path = songpath;
            sa.setXName(songname);
            oldmode = sa.getMode();
            Open();
            Play();
            menuitemplay.setEnabled(true);
            menuitempause.setEnabled(true);
            menuitemstop.setEnabled(true);
            bplay.setEnabled(true);
            bpause.setEnabled(true);
            bstop.setEnabled(true);
            menucontrol.setEnabled(true);
            menuview.setEnabled(true);
            menuabout.setEnabled(true);
            if(playlist.getPlayListLength() > 1){
                menuitemnext.setEnabled(true);
                menuitemprevious.setEnabled(true);
                bnext.setEnabled(true);
                bprevious.setEnabled(true);
            }
        }
        else if(state == 2)
            viewFileInfo();
        else if(state == 3)
        {
            sa.setXName("");
            Stop();
            menuitemplay.setEnabled(false);
            menuitempause.setEnabled(false);
            menuitemstop.setEnabled(false);
            bplay.setEnabled(false);
            bpause.setEnabled(false);
            bstop.setEnabled(false);
            if (playlist.getPlayListLength() <= 2){
                menuitemnext.setEnabled(false);
                menuitemprevious.setEnabled(false);
                bnext.setEnabled(false);
                bprevious.setEnabled(false);
            }
            else if(playlist.getPlayListLength() > 2){               
                menuitemnext.setEnabled(true);
                menuitemprevious.setEnabled(true);
                bnext.setEnabled(true);
                bprevious.setEnabled(true);
            }
        }
        else if(state == 4)
        {
            sa.setXName("");
            Stop();
            bplay.setEnabled(false);
            bpause.setEnabled(false);
            bstop.setEnabled(false);
            bnext.setEnabled(false);
            bprevious.setEnabled(false);
            menuview.setEnabled(false);
            menuabout.setEnabled(false);
            menucontrol.setEnabled(false);
            songname = "";
            path = "";           
        }
        else if(state == 5){
            if (playlist.getPlayListLength() == 2) {
                bnext.setEnabled(false);
                bprevious.setEnabled(false);
                menuitemnext.setEnabled(false);
                menuitemprevious.setEnabled(false);
            } else if (playlist.getPlayListLength() > 2) {
                bnext.setEnabled(true);
                bprevious.setEnabled(true);
                menuitemnext.setEnabled(true);
                menuitemprevious.setEnabled(true);
            } else {
                bnext.setEnabled(false);
                bprevious.setEnabled(false);
                menuitemnext.setEnabled(false);
                menuitemprevious.setEnabled(false);
                menuview.setEnabled(false);
                menuabout.setEnabled(false);
                menucontrol.setEnabled(false);
            }
           
        }
    }
    public String getOntopState(){
        if(menuitemontop.isSelected())
            return "ontop";
        else
            return "nonontop";
    }
    public String getShuffleState(){
        if(menuitemshuffle.isSelected())
            return "shuffle";
        else
            return "nonshuffle";
    }
    public String getRepeatState(){
        if(menuitemrepeatcurrent.isSelected()){
            return "current";            
        }else if(menuitemrepeatall.isSelected()){
            return "all";
        }else
            return "none";
            
    }
    public String getGainNumber(){        
        return Double.toString(2*gain);
    }
    public String getPanNumber(){
        return Double.toString(pan);
    }
    public boolean isControlable(){
        return menucontrol.isEnabled();
    }
    public void viewFileInfo(){
    }
    public String getSongName(){
        return songname;
    }
    public void setController(BasicController bc) {
        throw new UnsupportedOperationException("Cai nay khong su dung");

    }
    private void seekBytes(int x){
        try {
            oldmode = sa.getMode();
            mp.seek((long) (x * bytesperpixel));
            sa.setMode(oldmode);
            playerstate = PLAY;
            mp.setGain(gain);
            mp.setPan(pan);
            sa.setStatus(1);
        } catch (BasicPlayerException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void setBlinkPosition(int bytesread){
        blinkposition = (int)(305*(double)bytesread/playingfilesize);
        sa.setBlinkPosition(blinkposition);
    }
    
    public void processDnD(Object data){
        if (data instanceof List)
        {
            List al = (List) data;
            int songnum = 0;
            String song = "";
            path = al.get(0).toString().substring(0, al.get(0).toString().lastIndexOf('\\')+1);
            String sname = "";
            String ext = "";
            for(int i = 0; i < al.size(); i++){
                song = al.get(i).toString();
                ext = song.substring(song.lastIndexOf('.')+1, song.length()).toLowerCase();
                if((ext.compareTo("mp1")==0)||(ext.compareTo("mp2")==0)||(ext.compareTo("mp3")==0)||(ext.compareTo("ogg")==0)||(ext.compareTo("wav")==0)||(ext.compareTo("wsz")==0)||(ext.compareTo("snd")==0)||(ext.compareTo("aifc")==0)||(ext.compareTo("aif")==0)||(ext.compareTo("au")==0)||(ext.compareTo("spx")==0)||(ext.compareTo("flac")==0)||(ext.compareTo("ape")==0)||(ext.compareTo("mac")==0))
                    songnum++;
            }
            total_song = new String[songnum];
            songlist = new String[songnum];
            for(int i = 0, j =0; i < al.size(); i++){
                song = al.get(i).toString();
                sname = song.substring(song.lastIndexOf('\\')+1, song.length());
                ext = song.substring(song.lastIndexOf('.')+1, song.length()).toLowerCase();
                if((ext.compareTo("mp1")==0)||(ext.compareTo("mp2")==0)||(ext.compareTo("mp3")==0)||(ext.compareTo("ogg")==0)||(ext.compareTo("wav")==0)||(ext.compareTo("wsz")==0)||(ext.compareTo("snd")==0)||(ext.compareTo("aifc")==0)||(ext.compareTo("aif")==0)||(ext.compareTo("au")==0)||(ext.compareTo("spx")==0)||(ext.compareTo("flac")==0)||(ext.compareTo("ape")==0)||(ext.compareTo("mac")==0)){
                    total_song[j] = sname;
                    songlist[j] = path + sname;
                    j++;
                }
            }
            playlist.addSong(total_song, path);
            playlist.addSong(songlist);
            if(playlist.getPlayListLength() == songnum){
                menuview.setEnabled(true);
                menuabout.setEnabled(true);
                menucontrol.setEnabled(true);
                songname = total_song[0];
                Open();
                Play();
                sa.setXName(songname);
                playlist.setCurrentIndex(0);
                bplay.setEnabled(true);
                bpause.setEnabled(true);
                bstop.setEnabled(true);
                bnext.setEnabled(false);
                bprevious.setEnabled(false);
                menuitemnext.setEnabled(false);
                menuitemprevious.setEnabled(false);
            }
            if(playlist.getPlayListLength() > 1){
                bnext.setEnabled(true);
                bprevious.setEnabled(true);
                menuitemnext.setEnabled(true);
                menuitemprevious.setEnabled(true);
            }
            if(!playlist.isVisible())
                playlist.setLocation(getX(), getY()+getHeight());
            playlist.setVisible(true);
        }
    }

    public void dragEnter(DropTargetDragEvent dtde) {
        
    }

    public void dragOver(DropTargetDragEvent dtde) {

    }

    public void dropActionChanged(DropTargetDragEvent dtde) {

    }

    public void dragExit(DropTargetEvent dte) {

    }

    public void drop(DropTargetDropEvent dtde) {
        try {
            DataFlavor[] dfs = dtde.getCurrentDataFlavors();
            DataFlavor tdf = null;
            if (DataFlavor.javaFileListFlavor.equals(dfs[0])) {
                tdf = dfs[0];
            }
            Transferable t = dtde.getTransferable();
            Object data = t.getTransferData(tdf);
            processDnD(data);
        }
        // Xu ly dock
        //Them option Reset Playlist position de chuyen vi tri cua playlist ve vi tri o duoi player
        catch (UnsupportedFlavorException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void setUserInfo(String text, String imagepath){
        if(!text.isEmpty())
            usertext = text; 
        if(usertext.equals("showsysinfo")){
            Properties props = System.getProperties();
            Iterator it = props.keySet().iterator();
            TreeMap map = new TreeMap();
            while (it.hasNext())
            {
                String key = (String) it.next();
                String value = props.getProperty(key);
                map.put(key, value);
            }
            it = map.keySet().iterator();
            while (it.hasNext())
                {
                    String key = (String) it.next();
                    String value = (String) map.get(key);
                    System.out.println(key + "=" + value + "\r\n");
                }
            sa.setMode(15);
            usertext = "Mr.D";
        }
        else if(usertext.equals("showoption")){
            File f = new File(optionstore);
            char[] cbuf = new char[(int)f.length()];
            FileReader fr;
            if(f.isFile()&&(f.exists()))
                try {
                    fr = new FileReader(optionstore);
                try {
                    fr.read(cbuf);
                } catch (IOException ex) {
                    Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
            String songn = new String(cbuf);
            DefaultListModel model = new DefaultListModel();
            String currentsong = "";
            int beginlink = 0;
            for(int i = 0; i < songn.length(); i++){
                if(songn.charAt(i) == 10){
                    currentsong = songn.substring(beginlink, i);
                    beginlink = i+1;
                    model.addElement(currentsong);
                }
            }
            String [] options = new String[10];
            for(int i = 0; i < 9; i ++)
                options[i] = "0";
            for(int i = 0; i < model.getSize(); i++){
                options[i] = model.getElementAt(i).toString();
            }
            System.out.println("Player X: "+options[0]);
            System.out.println("Player Y: "+options[1]);
            System.out.println("Playlist X: "+options[2]);
            System.out.println("Playlist Y: "+options[3]);
            System.out.println("Custom X: "+options[4]);
            System.out.println("Custom Y: "+options[5]);
            System.out.println("Visual mode: "+options[6]);
            System.out.println("User text: "+options[7]);
            System.out.println("User image path: "+options[8]);
            System.out.println("Selected file path: "+options[9]);
            setBounds(getX(), getY(), 300, 278);
            bplay.setBounds(60, 230, 60, 25);
            bprevious.setBounds(0,230, 60, 25);
            bpause.setBounds(120, 230, 60, 25);
            bstop.setBounds(180, 230, 60, 25);
            bnext.setBounds(240,230,60,25);
            sa.setMode(15);
            sa.repaint();
            usertext = "Mr.D";
        }
        else if(usertext.equals("showsonglist")){
//            File f = new File(songliststore);
//            char[] cbuf = new char[(int)f.length()];
//            FileReader fr;
//            if(f.isFile()&&(f.exists()))
//                try {
//                    fr = new FileReader(songliststore);
//                try {
//                    fr.read(cbuf);
//                } catch (IOException ex) {
//                    Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            } catch (FileNotFoundException ex) {
//                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
//            }
//            String songn = new String(cbuf);
//            DefaultListModel model = new DefaultListModel();
//            String currentsong = "";
//            int beginlink = 0;
//            for(int i = 0; i < songn.length(); i++){
//                if(songn.charAt(i) == 10){
//                    currentsong = songn.substring(beginlink, i);
//                    beginlink = i+1;
//                    model.addElement(currentsong);
//                }
//            }
//            String [] options = new String[model.getSize()];
//            for(int i = 0; i < 9; i ++)
//                options[i] = "0";
//            for(int i = 0; i < model.getSize(); i++){
//                options[i] = model.getElementAt(i).toString();
//                System.out.println("Song "+ (i+1) +": "+options[i]);
//            }
            System.out.println(playlist.listCurrentSong());
            setBounds(getX(), getY(), 300, 278);
            bplay.setBounds(60, 230, 60, 25);
            bprevious.setBounds(0,230, 60, 25);
            bpause.setBounds(120, 230, 60, 25);
            bstop.setBounds(180, 230, 60, 25);
            bnext.setBounds(240,230,60,25);
            sa.setMode(15);
            sa.repaint();
            usertext = "Mr.D";
        }
        else if(usertext.equals("showdirlist")){
//            File f = new File(urlliststore);
//            char[] cbuf = new char[(int)f.length()];
//            FileReader fr;
//            if(f.isFile()&&(f.exists()))
//                try {
//                    fr = new FileReader(urlliststore);
//                try {
//                    fr.read(cbuf);
//                } catch (IOException ex) {
//                    Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
//                }
//            } catch (FileNotFoundException ex) {
//                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
//            }
//            String songn = new String(cbuf);
//            DefaultListModel model = new DefaultListModel();
//            String currentsong = "";
//            int beginlink = 0;
//            for(int i = 0; i < songn.length(); i++){
//                if(songn.charAt(i) == 10){
//                    currentsong = songn.substring(beginlink, i);
//                    beginlink = i+1;
//                    model.addElement(currentsong);
//                }
//            }
//            String [] options = new String[model.getSize()];
//            for(int i = 0; i < 9; i ++)
//                options[i] = "0";
//            for(int i = 0; i < model.getSize(); i++){
//                options[i] = model.getElementAt(i).toString();
//                System.out.println("Song dir "+ (i+1) +": "+options[i]);
//            }
            System.out.println(playlist.listCurrentUrl());
            setBounds(getX(), getY(), 300, 278);
            bplay.setBounds(60, 230, 60, 25);
            bprevious.setBounds(0,230, 60, 25);
            bpause.setBounds(120, 230, 60, 25);
            bstop.setBounds(180, 230, 60, 25);
            bnext.setBounds(240,230,60,25);
            sa.setMode(15);
            sa.repaint();
            usertext = "Mr.D";
        }
        else if(usertext.equals("showpathlist")){
            System.out.println(playlist.listAll());
            setBounds(getX(), getY(), 300, 278);
            bplay.setBounds(60, 230, 60, 25);
            bprevious.setBounds(0,230, 60, 25);
            bpause.setBounds(120, 230, 60, 25);
            bstop.setBounds(180, 230, 60, 25);
            bnext.setBounds(240,230,60,25);
            sa.setMode(15);
            sa.repaint();
            usertext = "Mr.D";
        }
        if(!imagepath.isEmpty()){
            userimagepath = imagepath;            
            Image im = getToolkit().getImage(userimagepath);
            this.setIconImage(im);
            playlist.setIconImage(im);
            ct.setIconImage(im);
            menuitemskincustom.setSelected(true);
        }
        sa.setUserInfo(usertext, userimagepath);
        if(!imagepath.isEmpty()){
            setBounds(getX(), getY(), 300, 278);
            bplay.setBounds(60, 230, 60, 25);
            bprevious.setBounds(0,230, 60, 25);
            bpause.setBounds(120, 230, 60, 25);
            bstop.setBounds(180, 230, 60, 25);
            bnext.setBounds(240,230,60,25);
            sa.setMode(11);
            sa.repaint();
        }
        if(!text.isEmpty()){
            setBounds(getX(), getY(), 300, 278);
            bplay.setBounds(60, 230, 60, 25);
            bprevious.setBounds(0,230, 60, 25);
            bpause.setBounds(120, 230, 60, 25);
            bstop.setBounds(180, 230, 60, 25);
            bnext.setBounds(240,230,60,25);
            sa.setMode(6);
            sa.repaint();
        }
        if(usertext.equals("hiddenhelp")){
            setBounds(getX(), getY(), 300, 278);
            bplay.setBounds(60, 230, 60, 25);
            bprevious.setBounds(0,230, 60, 25);
            bpause.setBounds(120, 230, 60, 25);
            bstop.setBounds(180, 230, 60, 25);
            bnext.setBounds(240,230,60,25);
            sa.setMode(15);
            sa.repaint();
            usertext = "Mr.D";
        }
    }
    public void initialize(){
        threadforgravity.start();
        addKeyListener(this);
    }
    public void run() {
        while(isrunning){
            try{
                Thread.sleep(10);
            }
            catch(Exception e){}
            if(isbouchselected){
                if((frameposx + getWidth()) > screensize.width)
                    directionx = true;
                else if(frameposx < 0)
                    directionx = false;
                if((frameposy + getHeight()) > screensize.height)
                    directiony = true;
                else if(frameposy  < 0)
                    directiony = false;
                if(!isholding){
                    if(directionx)
                        frameposx --;
                    else
                        frameposx ++;
                    if(directiony)
                        frameposy --;
                    else
                        frameposy ++;
                }
                setLocation(frameposx, frameposy);
            }
            if((menuitemgravityeffect.isSelected())&&(frameposy + getHeight() < screensize.height))
                isgravityselected = true;
            else{
//                inivelocityy = inivelocityy + 9.8*gravitycurrenttime;
//                gravityenabletime = System.currentTimeMillis();
//                System.out.println("inivelocityy == " + inivelocityy);
            }
            if(isgravityselected){
                gravitycurrenttime =(System.currentTimeMillis() - gravityenabletime)*0.003;
                frameposy += (int)(inivelocityy * gravitycurrenttime + 0.5 * (9.8) * gravitycurrenttime * gravitycurrenttime);
                System.out.println((int)(inivelocityy * gravitycurrenttime + 0.5 * (9.8) * gravitycurrenttime * gravitycurrenttime));
                velocity_y = inivelocityy + (-9.8) * gravitycurrenttime;
                if(!isholding)
                    setLocation(frameposx, frameposy);
                else
                    setEffectStartingPos();
//                System.out.println("Updating location");
//                System.out.println("frameposy == " + frameposy);
            }
            if(!isholding&&(frameposy + getHeight() >= screensize.height)){
                gravityenabletime = System.currentTimeMillis();
                gravitycurrenttime = 0;
                inivelocityy = -velocity_y;
                System.out.println("Time to Elastic");
            }

//                isgravityselected = false;
            
        }
    }

    public void keyTyped(KeyEvent e) {
        
    }

    public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_ESCAPE){
            try {
                mp.stop();
                sa.setXName("");
                playerstate = STOP;
            } catch (BasicPlayerException ex) {}
            catch(Exception exc){}
            try {
                FileWriter fw = new FileWriter(songliststore);
                fw.write(playlist.listSong());
                fw.close();
                fw = new FileWriter(urlliststore);
                fw.write(playlist.listUrl());
                fw.close();
                fw = new FileWriter(optionstore);
                fw.write(getX()+"\n"+getY()+"\n"+playlist.getX()+"\n"+playlist.getY()+"\n"+ct.getX()+"\n"+ct.getY()+"\n"+sa.getMode()+"\n"+usertext+"\n"+userimagepath+"\n"+selectedfilepath+"\n"+sa.getTextStatus()+"\n"+getOntopState()+"\n"+getShuffleState()+"\n"+getRepeatState()+"\n"+getGainNumber()+"\n"+getPanNumber()+"\n");
                fw.close();
            } catch (IOException ex) {
                Logger.getLogger(Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
    //                System.out.println(playlist.listSong());
            System.gc();
            System.exit(0);
        }
    }

    public void keyReleased(KeyEvent e) {

    }


    // Luu vi tri cua player, playlist, visualization mode, text user, path image user, gain, pain, byteread
    // Xu ly skin
}
